<template>
  <PhoneForm ref="PhoneForm" :formList.sync="formLists" :formConf="formAttrs" />
</template>

<script>
import PhoneForm from "@/components/formGenerator/formComponents/phoneForm.vue";
import {
  deepClone,
  setFormValue,
  arrayToObject,
} from "@/components/formGenerator/utils";
import "./common/initPhone";
import store from "@/store";
import mixins from "./common/mixins";

export default {
  name: "FGPhoneForm",
  mixins: [mixins],
  components: {
    PhoneForm,
  },
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: {
    value: {
      type: [String, Object],
      default: "",
    },
    // 传入对应的key & value
    form: {
      type: Object,
      default: () => {},
    },
    // 传入的对应的[key:'',value:'']
    formArray: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      formLists: [],
      formAttrs: {},
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    // 传的value值是否为String类型
    isString() {
      return typeof this.value === "string";
    },
  },
  methods: {
    init() {
      let value = deepClone(this.value);
      let form = this.form;
      if (this.formArray.length) form = arrayToObject(this.formArray);
      if (this.isString) {
        value = JSON.parse(this.value || "{}");
      }
      if (value && value.list) {
        this.formLists = setFormValue(deepClone(value?.list || []), form);
        this.formAttrs = deepClone(value);
        delete this.formAttrs?.list;
      }
    },
    validateForm(cb) {
      this.$refs["PhoneForm"].validateForm((valid, form, list) => {
        let newValue = deepClone({ ...this.formAttrs, list });
        if (this.isString) {
          newValue = JSON.stringify(newValue);
        }
        this.$emit("update", newValue);
        this.$emit("submit", form, newValue);
        cb(valid, form, newValue);
      });
    },
    submitForm(cb) {
      this.$refs["PhoneForm"].submitForm((form, list) => {
        let newValue = deepClone({ ...this.formAttrs, list });
        if (this.isString) {
          newValue = JSON.stringify(newValue);
        }
        this.$emit("update", newValue);
        this.$emit("submit", form, newValue);
        cb(form, newValue);
      });
    },
    // 重置
    resetForm() {
      this.$refs["PhoneForm"].resetForm();
    },
  },
  // 销毁组件时清空store
  destroyed() {
    store.commit("SET_CSSLIST", []);
    store.commit("SET_EVENTLIST", []);
  },
};
</script>

<style lang="scss" scoped></style>
